package utils
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	/**
	 * 位图动画基础处理。
	 * @author 青竹
	 *
	 */
	public class BitmapAnimation extends Bitmap
	{
		protected var cache:BitmapData;
        protected var bitmap:BitmapData;

		protected var row:int=1;//行
		protected var col:int=1;//列

		protected var clip:Rectangle;

		protected var tileWidth:Number
		protected var tileHeight:Number
		protected var tolFrame:int;
		protected var frame:int=0;
		protected var _isSize:Boolean;
		
		/**
		 *
		 * @param bitmapData
		 * @param rows
		 * @param cols
		 * @param tolFrame
		 * @param isSize 指明rows,cols是行列还是宽高。
		 *
		 */
		public function BitmapAnimation(bitmapData:BitmapData=null,rows:Number=0,cols:Number=0,tolFrame:int=0,isSize:Boolean=false)
		{
			begin(bitmapData,rows,cols,tolFrame,isSize)
			//super();
			//this.addEventListener(Event.ADDED_TO_STAGE,onStage);
			//this.addEventListener(Event.ADDED_TO_STAGE,onStage);
		}
		
		public function begin(bitmapData:BitmapData,rows:Number,cols:Number,tolFrame:int=0,isSize:Boolean=false):void{
			_pos=new Point(0,0);
			_isSize=isSize;
			if(tolFrame>0){
				this.tolFrame=tolFrame;
			}else{
				if(!isSize) this.tolFrame=rows*cols;
			}
			row=rows;
			col=cols;
			cache=bitmapData;
			init();
		}

	    protected function init():void{
				if(_isSize){
					tileWidth=row
					tileHeight=col;
					if(cache){
						row=Math.floor(cache.width/row);
						col=Math.floor(cache.height/col);
					}
				}else{
//					row=row;
//					col=col;
					if(cache){
						tileWidth=cache.width/row;
						tileHeight=cache.height/col;
					}
				}

 				bitmap=new BitmapData(tileWidth,tileHeight,true,0xff0000);
				clip=new Rectangle(0,0,tileWidth,tileHeight);
				this.bitmapData=bitmap;
		}
		
		private var _pos:Point//=new Point(0,0);
		internal var _isPlay:Boolean=true;
		public function play():void{
		    _isPlay=true;
		}
		public function stop():void{
			_isPlay=false
		}
		public function gotoAndPlay(v:int):void{
			frame=v;
			_isPlay=true;
		}
		public function gotoAndStop(v:int):void{
			frame=v;
			_isPlay=true;
			reader();
			_isPlay=false;
		}
		public var isLoop:Boolean=true;
		public var playEnd:Function;
		public function reader():void{
			if(!_isPlay) return; 
			if(frame>=tolFrame){
				if(!isLoop) {
					_isPlay=false;
					if(playEnd!=null){
					   playEnd(this);
					}
				}
			    frame=0;
			}
			if(cache==null) return;
            clip.x=(frame%row)*tileWidth;
			clip.y=(frame/row>>0)*tileHeight;
			frame++;

			bitmap.lock();
			bitmap.copyPixels(cache,clip,this._pos);
			bitmap.unlock();
		}
	}
}